<template>
  <div  v-title="'商品管理 - 世外生活运营平台'">
    <mk-breadcrumb  :breadcrumb-data="breadcrumbData"></mk-breadcrumb>
    <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-fixedHeightSmall)+'px'}]">
      <div class="PublicListStyle MkProductMgt">
        <mk-search-component :formArr="formArr"  inputPlaceholder = "商品ID/商品名称/店铺名称" @startSearch="fun_call_search">
        <span slot="slot_1">
             <el-popover placement="bottom" title="" width="160"  trigger="hover" popper-class='MkProductMgt_tip'>
            <div>
              <div class="tipBtn" @click="upOrDownGoods(true)">上架</div>
              <div class="tipBtn" @click="upOrDownGoods(false)">下架</div>
              <div class='tipBtn' v-for="item in subjectSelect" :key = 'item.id'>
                {{item.name}}
               <span style="margin:0 10px;">|</span>
                <i class="el-icon-check" style="padding:5px;" @click="addSubject(item.id)"></i>
                <i class="el-icon-close" style="padding:5px;" @click="deleteSubject(item.id)"></i>
              </div>
            </div>
            <el-button type="primary" size="" class='btn-create floatRight' slot="reference">批量操作</el-button>
          </el-popover>
        </span>
          <div  slot="slot_2" class="search-result-amount textAlignRight">
            <el-popover placement="bottom" title="" width="160"  trigger="hover" popper-class='MkProductMgt_tip'>
              <div>
                <div class="tipBtn" @click="upOrDownGoods(true)">上架</div>
                <div class="tipBtn" @click="upOrDownGoods(false)">下架</div>
                <div class='tipBtn' v-for="item in subjectSelect" :key = 'item.id'>
                  {{item.name}}
               <span style="margin:0 10px;">|</span>
                  <i class="el-icon-check" style="padding:5px;" @click="addSubject(item.id)"></i>
                  <i class="el-icon-close" style="padding:5px;" @click="deleteSubject(item.id)"></i>
                </div>
              </div>
              <el-button type="primary" size="" class='btn-create floatRight' slot="reference">批量操作</el-button>
            </el-popover>
          </div>
        </mk-search-component>

      <div class="tabContainer primary_bg trHasCursor"  v-loading="loadingTab"
           element-loading-text="拼命加载中">
        <el-table
          @selection-change="handleSelectionChange"
          @cell-click="clickCell"
          :data="dataArr.elements"
          style="width: 100%">
          <el-table-column
            type="selection"
            width="50">
          </el-table-column>
          <el-table-column
            prop="goodsNumber"
            label="商品ID"
            width="">
          </el-table-column>
          <el-table-column
            prop="goodsName"
            label="商品名称"
            show-overflow-tooltip
            width="200">
          </el-table-column>
          <el-table-column
            prop="shopName"
            label="店铺名称"
            show-overflow-tooltip
            width="">
          </el-table-column>
          <el-table-column
            prop="siteName"
            label="站点名称"
            show-overflow-tooltip
            width="">
          </el-table-column>
          <el-table-column
            prop="categoryName"
            label="商品分类">
          </el-table-column>

          <el-table-column
            prop="minPrice"
            width=""
            label="价格（元）">
          </el-table-column>
          <el-table-column
            prop="stock"
            width=""
            label="库存">
          </el-table-column>
          <el-table-column
            prop="subjectName"
            width=""
            show-overflow-tooltip
            label="专题">
          </el-table-column>
          <el-table-column
            prop=""
            width="100"
            label="上架">
            <template slot-scope="scope">
              <el-switch
                active-color="#3bc0c3" inactive-color="#b6c2c9" v-model='scope.row.published' @click.stop.native @change='upOrDownGoodsInTab(scope.row)' class=' marginTop'>
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            prop="sort"
            width=""
            label="排序">
            <template slot-scope='scope' >
              <div class="sortDiv">
                <el-input
                  :readonly=true
                  placeholder=""
                  v-model='scope.row.sort'
                  :ref="'sort_'+scope.$index"
                  @click.stop.native
                >
                  <i class="el-icon-edit" :ref="'btn_'+scope.$index" slot="append" @click="editObj($event,scope.row.goodsId,scope.$index)"></i>
                </el-input>

              </div>
              <!--<div v-else style="color:#c6cdd2;padding-left:8px;">-->
              <!--{{scope.row.sort}}-->
              <!--</div>-->
              {{scope.$index}}
            </template>
          </el-table-column>
        </el-table>
        <el-pagination v-if='dataArr.elements.length>0'
                       @current-change="loadData"
                       :current-page="dataArr.page"
                       :page-size="dataArr.size"
                       layout="total, prev, pager, next"
                       :total="dataArr.totalAmount">
        </el-pagination>
      </div>
    </div>
    </el-scrollbar>
  </div>
</template>

<script>
  import MkBreadcrumb from '../../components/MkBreadcrumb.vue'
  import productService from '../../services/product'
  import { mapState } from 'vuex'
  export default {
    name: 'MkProductMgt',
    components: {
      MkBreadcrumb
    },
    watch: {

    },
    computed: mapState({
      bodyHeight: state => state.global.bodyHeight,
      fixedHeightSmall: state => state.global.fixedHeightSmall,
//      productCategory: state => state.product.productCategory,
      productCategory (state) {
        this.$set(this.formArr,1,{
          formLabel:'商品分类',
          searchName:'categoryArr',
          dataType:'array',
          componentType:'Cascader',
          changeOnSelect:true,
          optionsArr:state.product.productCategory,
          defaultProps:{
            label:'name',
            value: 'id',
            children: 'children'
          }
        })
      },
      subject (state) {
        this.$set(this.formArr,3,{
          formLabel:'专题',
          searchName:'subjectId',
          dataType:'string',
          componentType:'Select',
          optionsArr:state.product.subject,
        });
        return state;
      },
      siteSelect: state => {
        let arr = [];
        let data = state.site.siteTree;
        arr.push({id:'',name:'全部'});
        if(data.children){
          for(var i=0;i<data.children.length;i++) {
            let item = data.children[i];
            if(item.children && item.children.length>0) {
              arr.push(item);
            }
          }
        }
        return arr;
      }
    }),
    mounted: function() {
      this.$set(this.formArr,2,{
        formLabel:'上架',
        searchName:'published',
        dataType:'string',
        componentType:'Select',
        optionsArr:[{name:'已上架',value:'true'},{name:'已下架',value:'false'}],
      });

      this.loadSiteData();

//      this.loadSubject();
//      this.loadCategory();
      this.$store.dispatch("loadProductCategory",{fields:'children,hasImage,id,name,parentId,status,image,parentName'}).then(()=>{
        return this.productCategory
      });
      this.$store.dispatch('loadSubjectData',{fields:'id,name,value'}).then((data)=>{
      	this.subjectSelect = data.data;
        return this.subject;
      })
    },

    activated(){
      this.loadData(1);
    },

    methods: {
      fun_call_search(search,input){
        this.searchCondition.published = search.published;
        this.searchCondition.categoryId = search.categoryArr[search.categoryArr.length - 1];
        this.searchCondition.siteId = search.siteArr[search.siteArr.length - 1];
        this.searchCondition.subjectId = search.subjectId;
        this.searchCondition.search = input;
        this.loadData(1);
      },
      loadSiteData(){
        this.$store.dispatch('loadSiteTree',{fields:'id,name'}).then((data) =>{
          let arr = [{id:'',name:'全部'}];
          if(data.data.children){
            for(var i=0;i<data.data.children.length;i++) {
              let item = data.data.children[i];
              if(item.children && item.children.length>0) {
                arr.push(item);
              }
            }
          }
          this.$set(this.formArr,0,{
            formLabel:'服务站点',
            searchName:'siteArr',
            dataType:'array',
            componentType:'Cascader',
            changeOnSelect:false,
            optionsArr:arr ,
            defaultProps:{
              label:'name',
              value: 'id',
              children: 'children'
            }
          })
        });
      },
      deleteSubject(subjectId) {
        if(this.selectedRows.length>0) {
          var arr = [];
          this.selectedRows.forEach(function(item) {
            arr.push(item.goodsId)
          });
          productService.deleteSubjectServer({goodsIds: arr.join(','),subjectId: subjectId},data=>{
            this.$message.success('取消成功');
            this.loadData();
          })
        }else{
          this.$message.warning('请选择商品');
          return;
        }
      },
      addSubject(subjectId) {
        if(this.selectedRows.length>0) {
          var arr = [];
          this.selectedRows.forEach(function(item) {
            arr.push(item.goodsId)
          });
          productService.addSubjectServer({goodsIds: arr.join(','),subjectId: subjectId},data=>{
            this.$message.success('设置成功');
            this.loadData();
          })
        }else{
          this.$message.warning('请选择商品');
          return;
        }
      },
      upOrDownGoodsInTab(obj) {
        var str = obj.published? '上架':'下架';
        this.$confirm('您是确定要'+str+'此商品?', '商品'+str, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          closeOnClickModal: false,
          closeOnPressEscape:false,
          customClass: 'confirmBox_warning'
        }).then(() => {
          productService.upOrDownGoodsServer({published: obj.published, goodsIds:obj.goodsId}, () => {
            this.$message.success('成功'+str+'商品');
            this.loadData();
          },()=>{
            obj.published = str == '上架'? false: true;
          });
        }).catch(() => {
          obj.published = str == '上架'? false: true;
        });
      },
      upOrDownGoods(state) {
        if(this.selectedRows.length>0) {
          let str = state? '上架':'下架';
          this.$confirm('您是确定要'+str+'此商品?', '商品'+str, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            closeOnClickModal: false,
            closeOnPressEscape:false,
            customClass: 'confirmBox_warning'
          }).then(() => {
            var arr = [];
            this.selectedRows.forEach(function(item) {
              arr.push(item.goodsId)
            })
            productService.upOrDownGoodsServer({published: state, goodsIds:arr.join(',')}, () => {
              this.$message.success('成功'+str+'商品');
              this.loadData();
            },()=>{
            });
          }).catch(() => {
          });
        }else{
          this.$message.warning('请选择商品');
          return;
        }
      },
      handleSelectionChange(selection) {
        this.selectedRows = selection;
      },
      loadCategory() {},

      loadData(page) {
        if(page) {
            this.searchCondition['page.pn'] = page;
        }
        this.loadingTab = true;
        productService.loadProductServer(this.searchCondition,data=>{
          this.dataArr = data.data;

          this.$nextTick(()=> {
            let arr=[];
            for(var i=0;i<data.data.elements.length;i++) {
              arr.push(data.data.elements[i].sort)
            }
            this.listArr=arr;
            for(var i=0;i<arr.length;i++) {
              if(this.$refs['btn_'+i]){
                this.$refs['btn_'+i].className='el-icon-edit';
              }
              if(this.$refs['sort_'+i]){
                let inputElement=this.$refs['sort_'+i].$el.firstElementChild;
                inputElement.setAttribute('readonly','readonly');
              }
            }
          })

          this.loadingTab = false;
        })

      },
      loadSubject() {},

      editObj(ev,goodsId,index) {
        var inputElement=this.$refs['sort_'+index].$el.firstElementChild;
        if(ev.target.getAttribute('class') == 'el-icon-edit'){//编辑状态的时候
          //将所有图标置为编辑状态，输入框只读
          for(var i=0;i<this.listArr.length;i++) {
            if(this.$refs['btn_'+i]){
              this.$refs['btn_'+i].className='el-icon-edit';
            }
            if(this.$refs['sort_'+i]){
              let inputElement=this.$refs['sort_'+i].$el.firstElementChild;
              inputElement.value=this.listArr[i];
              inputElement.setAttribute('readonly','readonly');
            }

            for(var j=0;j<this.dataArr.elements.length;j++) {
              this.dataArr.elements[j].sort = this.listArr[j];
            }

          }
          //只讲当前点击的图标置为√（提交），且可写，获得焦点
          ev.target.setAttribute('class','el-icon-check');
          inputElement.removeAttribute('readonly');
          inputElement.focus();
        }else{//提交状态的时候
          let value= (inputElement.value+'').trim();
          if(value == "") {
            inputElement.value=this.listArr[index];
            inputElement.focus();
            this.$message.warning('不能为空')
          }else if(!(/^[1-9]{1}[0-9]{0,2}$/).test(value)){
            inputElement.value=this.listArr[index];
            inputElement.focus();
            this.$message.warning( '请输入1-999的数字');
          }else{
            let params = {
              categoryId: this.searchCondition.categoryId,
              siteId: this.searchCondition.siteId,
              sortValue: value,
              subjectId: this.searchCondition.subjectId,
              goodsId: goodsId,
            }
            productService.productSortServer(params,data=>{
              this.$message.success('修改成功')
              this.loadData();
            },()=>{

            })
          }

        }
      },
      clickCell(row, column, cell, event) {
        if(column.type == 'default') {
          this.$router.push({path:'/productDetail',query:{id: row.goodsId}})
        }
      },
    },
    data(){
      return{
        subjectSelect:[],
        formArr:[],
        selectedRows: [],
        listArr: [],
        loadingTab: false,
        dataArr: {
          elements: [],
          page: '',
          size: '',
          totalAmount: ''
        },
        searchCondition: {
          'page.pn':1,
          'page.size':10,
          published:'',
          categoryId:'',
          search: '',
          subjectId: '',
          siteId:'',
        },
        breadcrumbData: {
          list: [
            {name:'商品管理',path: null, clickAble: false},
            {name: '商品列表',path: null, clickAble: false}
          ],
          returnData: {
            isReturn: false, path: null
          },
          iconName: 'product-icon',
        }
      }
    }
  }
</script>
<style lang="less">
  @import '../../assets/style/main.less';
  .MkProductMgt_tip[x-placement^="bottom"] .popper__arrow::after{
    border-bottom-color: @menuBackColor1!important;
  }
  .MkProductMgt_tip{
    .my-border-radius(5px);
    line-height: 40px !important;
    width:180px!important;
    padding:15px 0;
    color:#fff;
    background-color:#1f3a3d;
    .tipBtn{
      padding-left:20px;
      &:hover{
        background-color:@primaryColor;
        cursor:pointer;
      }
    }
    i{
      &:hover{
        color:#3bc0c3;
        .my-border-radius(3px);
        background: white;
      }
    }
  }
  .MkProductMgt{
    .tabContainer{
      .el-checkbox{
        margin-right:0;
      }
    }

    .primary_bg .el-table--enable-row-hover .el-table__body tr:hover > td .el-input__inner{
      background-color:@hoverGreenColor;
    }

    .sortDiv {
      width:70px;
      height:100%;
      .el-input-group__append{
        display: none;
        padding-left:0px;
        padding-right:0px;
        .el-icon-edit,.el-icon-check{

          padding:8px 5px;
        }
      }
      .el-input__inner{
        padding-left:5px;
        padding-right:0px;
        height:30px;
        background:white;
      }
      &:hover{
        .el-input-group__append{
          display: table-cell;
          &:hover{
            .el-icon-edit,.el-icon-check{
              &:hover{
                .my-opacity(0.8);
              }
            }
          }
        }
        .el-input__inner{
          background:#f0f3f6!important;
        }
      }
    }
  }
</style>
